import React, { useState, useEffect } from 'react';
import { getVehicleRecords } from '../services/api';

const VehicleRecords = () => {
  const [records, setRecords] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [filter, setFilter] = useState('');

  useEffect(() => {
    // 首次加载数据
    const fetchRecords = async (showLoading = true) => {
      try {
        if (showLoading) {
          setLoading(true);
        }
        const response = await getVehicleRecords();
        setRecords(response.data);
        if (showLoading) {
          setError(null);
        }
      } catch (err) {
        console.error('获取车辆记录失败:', err);
        if (showLoading) {
          setError('获取车辆记录失败，请稍后重试');
        }
      } finally {
        if (showLoading) {
          setLoading(false);
        }
      }
    };

    // 首次加载显示loading状态
    fetchRecords(true);
    
    // 设置定时刷新 - 车辆记录属于不太重要的数据，使用5秒刷新
    const intervalId = setInterval(() => {
      // 后续轮询不显示loading状态
      fetchRecords(false);
    }, 5000); // 每5秒刷新一次
    
    return () => clearInterval(intervalId);
  }, []);

  const getStatusBadge = (status) => {
    switch (status) {
      case 'direct_entry':
        return <span className="px-2 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800">直接进入</span>;
      case 'reserved_entry':
        return <span className="px-2 py-1 text-xs font-semibold rounded-full bg-purple-100 text-purple-800">预约进入</span>;
      case 'exited':
        return <span className="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">已离开</span>;
      default:
        return <span className="px-2 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-800">{status}</span>;
    }
  };

  const filteredRecords = records.filter(record => 
    filter === '' || record.plate_number.toLowerCase().includes(filter.toLowerCase())
  );

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
          <p>{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold text-gray-800">车辆进出记录</h1>
      </div>
      
      <div className="bg-white rounded-lg shadow-md">
        <div className="p-4 border-b border-gray-200">
          <input
            type="text"
            placeholder="搜索车牌号..."
            className="w-full md:w-64 px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            value={filter}
            onChange={(e) => setFilter(e.target.value)}
          />
        </div>
        
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  ID
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  车牌号
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  车位号
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  进入时间
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  离开时间
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  停车时长
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  状态
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {filteredRecords.map((record) => {
                // 计算停车时长
                let durationText = '-';
                if (record.entry_time && record.exit_time) {
                  const entryTime = new Date(record.entry_time);
                  const exitTime = new Date(record.exit_time);
                  const durationMs = exitTime - entryTime;
                  const hours = Math.floor(durationMs / (1000 * 60 * 60));
                  const minutes = Math.floor((durationMs % (1000 * 60 * 60)) / (1000 * 60));
                  durationText = `${hours > 0 ? `${hours}小时 ` : ''}${minutes}分钟`;
                }
                
                return (
                  <tr key={record.id}>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {record.id}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                      {record.plate_number}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {record.spot_number}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {record.entry_time ? new Date(record.entry_time).toLocaleString() : '-'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {record.exit_time ? new Date(record.exit_time).toLocaleString() : '-'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {durationText}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      {getStatusBadge(record.status)}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          
          {filteredRecords.length === 0 && (
            <p className="text-gray-500 text-center py-8">
              {filter ? '没有匹配的车辆记录' : '暂无车辆记录'}
            </p>
          )}
        </div>
      </div>
      
      <div className="bg-white rounded-lg shadow-md p-6">
        <h2 className="text-lg font-semibold text-gray-800 mb-4">车辆状态说明</h2>
        <div className="space-y-2">
          <div className="flex items-center">
            <span className="px-2 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800 mr-2">直接进入</span>
            <p>车辆直接进入停车场，无预约</p>
          </div>
          <div className="flex items-center">
            <span className="px-2 py-1 text-xs font-semibold rounded-full bg-purple-100 text-purple-800 mr-2">预约进入</span>
            <p>车辆通过预约进入停车场</p>
          </div>
          <div className="flex items-center">
            <span className="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800 mr-2">已离开</span>
            <p>车辆已经离开停车场</p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default VehicleRecords; 